# coding= utf-8

# 调用两个爬虫常见响应器和承载器
import requests
from bs4 import BeautifulSoup
url = 'http://www.csdn.net'
s1 = requests.Session()
s2 = requests.Session()
s3 = requests.Session()
# 获取头部信息

def get_post_headers():
    return {
        "Host":'passport.csdn.net',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0',
        'Accept-Encoding': 'gzip,deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Connection':'keep-alive',
        'Referer':'http://www.csdn.net/'
    }

# 解析网页
def get_post_data():
    username = input('请输入用户名:\n')
    password = input('请输入密码:\n')
    login_page = s2.get(url,headers=get_post_headers().text)
    # 提取It，execution,_eventId
    soup = BeautifulSoup(login_page,'html.parser')
    It = soup.find(attrs={'name':'It'})['value']
    execution = soup.find(attrs={'name':'execution'})['value']
    submit = soup.find(attrs={'name':'_eventId'})['value']
    return dict(username=username,password=password,It=It,execution=execution,_eventId=submit)

# 返回登陆过后的session
def login(post_data):
    s1.post(url,data=post_data,headers=get_post_headers())
    return s1

# 检测是否登陆正常
if __name__ == '__main__':
    s3 = login(get_post_data())
    # 检测是否正常登陆
    home_page = 'http://my.csdn.net/my/mycsdn'
    # 这里的headers不能用前面那个，因为Host等参数发生改变了，否则会出现500状态码
    headers = {
        'Host':'my.csdn.net',
        'User-Agent':'Mozilla/5.0'
                     '(Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0',
        'Upgrade-Insecure-Requests':'1',
        'Accept':'Accept'
    }
    resp =s3.get(home_page,headers='')
    print(resp.text)